﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using omsData;

namespace myomscl_web.Admin.UserControls
{
    public partial class ucMenuScreen : System.Web.UI.UserControl
    {
        public void LoadTree(string type, string value)
        {
            this.tvScreens.Nodes.Clear();

            using (OmsModelContainer context = new OmsModelContainer())
            {
                TreeNode root = new TreeNode("Screens");
                root.Value = string.Empty;
                if (type == "root")
                {
                    //root.Selected = true;
                }

                var listScreens = context.ListScreens.Include("DetailsScreen").ToList();
                foreach (var ls in listScreens)
                {
                    var lsNode = new TreeNode(ls.Name);
                    lsNode.Value = string.Format("ls,{0}", ls.Id);
                    if (type != null && type == "ls" && value == ls.Name)
                    {
                        lsNode.Selected = true;
                    }
                    root.ChildNodes.Add(lsNode);

                    if (ls.DetailsScreen != null)
                    {
                        var dsNode = new TreeNode(ls.DetailsScreen.Name);
                        dsNode.Value = string.Format("ds,{0}", ls.DetailsScreen.Id);
                        if (type != null && type == "ds" && value == ls.DetailsScreen.Name)
                        {
                            dsNode.Selected = true;
                        }
                        lsNode.ChildNodes.Add(dsNode);
                    }
                }

                this.tvScreens.Nodes.Add(root);

                if (type == "root" || string.IsNullOrEmpty(type))
                    this.tvScreens.CollapseAll();
                else
                {
                    if (type == "ls")
                        this.tvScreens.ExpandAll();
                }
            }
        }

        protected void tvScreens_SelectedNodeChanged(object sender, EventArgs e)
        {
            var selectedNode = this.tvScreens.SelectedNode;
            if (selectedNode != null || selectedNode.Parent == null)
            {
                if (string.IsNullOrEmpty(selectedNode.Value))
                {
                    TreeClick("root", null);
                }
                else
                {
                    var parameters = selectedNode.Value.Split(new char[] { ',' });
                    TreeClick(parameters[0], parameters[1]);
                }
            }
        }

        public event OnTreeClick TreeClick;
    }
}